package descentFly.server
{
	import UIFree.uif_Timer;
	
	import UIUtils.uif_util;
	import UIUtils.uif_json;
	
	import api_servers.api_myserver;
	
	import com.adobe.serialization.json.JSONDecoder;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	public class myserver extends api_myserver {
		public static var MODEL_NAME: String = 'fly_01';
		
		private var _querys	: Array;
		private var _timer	: Timer;
		
		public function myserver(a_sroot:Object) {
			super(a_sroot, df_servers.MODEL_URL, '429390', '2567b2f9c525b55c8fd0b226df3d06b7');
			_querys = new Array();
			_timer	= new Timer(2000, 1);
			_timer.addEventListener(TimerEvent.TIMER_COMPLETE, doTimerComplete);
		}
		
		protected function doTimerComplete(e: Event): void {
			sendQuerys();
		}
		
		protected function sendQuerys(): void {
			var send: Array;
			if (_querys.length > 0) {
				var params: Array = new Array();
				_querys.forEach(function(item: Object, i: int, arr: Array): void {
					params[i] = {pn:'query' + (i + 1).toString(), pv: MODEL_NAME + ';' + item.method + ';' + item.params};
				});
				params.push({pn:'querycount', pv: _querys.length});
				
				jsrHelper(params, function(data: Object): void {
					data.response.forEach(function(data: Object, i: int, arr: Array): void {
						if (send[i].func != null) send[i].func(data);
					})
					send.splice(0, send.length);
				});
				
				send = [].concat(_querys);
				_querys.splice(0, _querys.length);
			}
		}
		
		public function addQuery(a_method: String, str_params: String='', _handle: Function=null): void {
			var index: int = _querys.length;
			for (var i: int=0; i<_querys.length; i++)
				if (_querys[i].method == a_method) {
					index = i;
					break;
				}
			
			_querys[index] = {
				method	: a_method,
				params	: str_params,
				func	: _handle
			}
			if (!_timer.running) 
				_timer.start();
		}

		public function oneQuery(method: String, str_params: String='', _handle: Function=null, a_cache: Boolean = false, a_url: String = ''): void {
			var params: Array = [
				{pn:'querycount', pv: 1},
				{pn:'query1', pv: MODEL_NAME + ';' + method + ';' + str_params}
			];
			
			
			jsrHelper(params, _handle, method, a_cache, a_url);
		}
		
		public function startUser(uid: String, options: Object, handle: Function): void {
			user_id = uid;
			oneQuery('startUser', uid + ';' + uif_json.e(options), handle);
		}
	}
}